package com.hjm.common.utils.request;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xiujian on 2018/5/10 09:50.
 */
@SuppressWarnings("all")
public class SaopXml {

//    private static final Logger logger = Logger.getLogger(SignatureUtil.class);

    public static Map<String,String> paresXml(String xml) {
        try {
            Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element root = doc.getRootElement();
            List<Element> rootEl = root.elements();
            return parseElement(rootEl, 0);
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static Map<String,String> parseElement(List<Element> elements, int k) {
        Map<String,String> map=new HashMap<>();
        String keys = null;
        for (Element element : elements) {
            String key = "";
            String value = "";
            List<Element> em = element.elements();
            if (em.size() > 0) {
                k = k + 3;
                Map<String,String> map1=parseElement(em, k);
                map.putAll(map1);
            } else {
                if(keys != null){
                    map.put(keys, element.getTextTrim());
                }
                if(keys == null){
                    keys = element.getTextTrim();
                }
            }
        }
        return map;
    }

    public String getTop(int i) {
        StringBuffer sb = new StringBuffer();
        for (int k = 0; k < i; k++) {
            sb.append("-");
        }
        return sb.toString();
    }
}
